package itsm.isperp.module.service.task;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.task.TskInspectTemplateCiCheck;
import itsm.isperp.module.repository.task.TskInspectTemplateCiCheckMapper;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * 服务
 * 
 * @author lizx
 * @date 2015-11-09 11:25
 */
@Service
public class TskInspectTemplateCiCheckService extends
		BaseService<TskInspectTemplateCiCheck> {

	@Autowired
	protected TskInspectTemplateCiCheckMapper tskInspectTemplateCiCheckMapper;

	@Override
	public TskInspectTemplateCiCheckMapper getRepository() {
		return this.tskInspectTemplateCiCheckMapper;
	}

	public List<TskInspectTemplateCiCheck> findAllByTaskId(String taskId) {
		return this.tskInspectTemplateCiCheckMapper.findAllByTaskId(taskId);
	}

	public ResultMessage saveValues(HttpServletRequest req) {

		String[] ciCheckValues = req.getParameterValues("ciCheckValues");
		String[] ciCheckRemark = req.getParameterValues("ciCheckRemarks");
		String[] ciCheckCiIds = req.getParameterValues("ciCheckCiIds");
		String[] templateCheckIds = req.getParameterValues("templateCheckIds");

		if (templateCheckIds == null || templateCheckIds.length == 0) {
			return ResultMessage.success();
		}

		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		String id = req.getParameter("id");

		jdbcTemplate
				.execute("DELETE FROM tsk_inspect_template_ci_check WHERE task_id='"
						+ id + "'");

		for (int i = 0; i < templateCheckIds.length; i++) {

			if (StringUtils.isNoneBlank(ciCheckValues[i])
					|| StringUtils.isNoneBlank(ciCheckRemark[i])) {
				TskInspectTemplateCiCheck checks = new TskInspectTemplateCiCheck();
				checks.setTaskId(id);
				checks.setCiId(ciCheckCiIds[i]);
				checks.setTemplateCheckId(templateCheckIds[i]);
				checks.setCheckValue(ciCheckValues[i]);
				checks.setRemark(ciCheckRemark[i]);
				this.saveOrUpdate(checks);
			}
		}

		return ResultMessage.success();
	}
}
